//
//  NetworkTools.swift
//  MAGweibo
//
//  Created by MagicaL on 15/7/31.
//  Copyright © 2015年 MagicaL. All rights reserved.
//

import UIKit
import AFNetworking

private let MAGErrorDominName = "network error"

class NetworkTools: AFHTTPSessionManager {
    
    // 单例
    static let sharedTools : NetworkTools = {
        
        let baseURL = NSURL(string: "https://api.weibo.com/")
        let tools = NetworkTools(baseURL: baseURL)
        
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json","text/json","text/javascript","text/plain") as Set<NSObject>
    
        return tools
    }()

    // MARK: - OAuth 授权
    /// 应用程序信息
    private let clientId = "3763573571"
    private let appSecret = "d3e7a54be3676c0d067f252fa5d47c07"
    /// 回调地址
    let redirectUri = "http://www.baidu.com"

    /// 返回OAuth 授权地址
    func oauthUrl() -> NSURL {
    
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        return NSURL(string: urlString)!
    }
    
    /// 加载 Token
    func loadAccessToken(code: String, finished: (result: [String : AnyObject]?, error: NSError?) ->()){
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = [
            "client_id" : clientId,
            "client_secret" : appSecret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirectUri
        ]
        
        POST(urlString, parameters: params, success: { (_, JSON) -> Void in
            
            finished(result: JSON as? [String : AnyObject],error: nil)
            
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
            }
        }

    // MARK: - 加载用户数据
    /**
        加载用户信息
        参数1: uid        用户代号字符串
        参数2: finished    完成回调
    */
    func loadUserInfo(uid: String,finished:MAGFinshedCallBack) {
        // 判断 token 是否存在
        if UserAccount.loadAccount()?.access_token == nil {
            return
        }
        let urlString = "2/users/show.json"
        let params: [String : AnyObject] = ["access_token": UserAccount.loadAccount()!.access_token!,"uid": uid]
        requestGET(urlString, params: params, finished: finished)
    }


    // MARK: - 封装AFN网络方法,替换网络方法 第三方框架的网络代码全部集中
    /// 网络回调类型别名    typealias: 在Swift中用typealias来定义现有的类型可替代名称
    typealias MAGFinshedCallBack = (result: [String : AnyObject]?, error: NSError?)->()
    /**
        GET请求
        param:  urlString URL地址
        param:  params    参数字典
        param:  finished  完成回调
    */
    private func requestGET(urlString: String,params: [String : AnyObject],finished: MAGFinshedCallBack) {
    
        GET(urlString, parameters: params, success: { (_, JSON) -> Void in
            if let result = JSON as? [String : AnyObject]{
                // 有结果的回调 没有错误
                finished(result: result, error: nil)
            } else {
                /**
                    NSError
                    domain   :  错误的范围/大类别 通常是一个常量字符串
                    code     :  错误代号 一般专门定义一个 .h 来存放所有错误的编码 通常都是负数
                    userInfo :  可以传递一些附加的错误信息
                */
                // 结果为空的回调 同时没有错误
                let error = NSError(domain: MAGErrorDominName, code: -1, userInfo: ["errorMessage":"空数据"])
                finished(result: nil, error: error)
            }
            
            }) { (_, error) -> Void in
                // 有错误
                print(error)
                finished(result: nil, error: error)
        }

    }

}






